package com.ljc.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljc.dto.Result;
import com.ljc.entity.VoucherOrder;
import com.ljc.mapper.VoucherOrderMapper;
import com.ljc.service.ISeckillVoucherService;
import com.ljc.service.IVoucherOrderService;
import com.ljc.utils.RedisIdWorker;
import com.ljc.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.UUID;

@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;
    @Resource
    private RedisIdWorker redisIdWorker;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RabbitTemplate rabbitTemplate;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    // 消息队列负责异步创建秒杀订单
    @RabbitListener(queuesToDeclare = @Queue("seckill.queue"))
    public void seckillConsumer(String msg) {
        VoucherOrder voucherOrder = JSONUtil.parseObj(msg).toBean(VoucherOrder.class);
        proxy.createVoucherOrder(voucherOrder);
    }


    private IVoucherOrderService proxy;

    /**
     * 向消息队列发送消息
     */
    public void sendMessageToQueue(String message) {
        // 1、全局唯一的消息ID，需要封装到CorrelationData中
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        // 2、添加callback
        correlationData.getFuture().addCallback(
                result -> {
                    if (result.isAck()) {
                        // 3.1.ack，消息成功【消息投递到交换机】ACK
                        log.debug("消息发送成功, ID:{}", correlationData.getId());
                    } else {
                        // 3.2.nack，消息失败【消息没有投递到交换机】NACK
                        log.error("消息发送失败, ID:{}, 原因{}", correlationData.getId(), result.getReason());
                    }
                },
                // 3.3.没收到消息回应
                ex -> log.error("消息发送异常, ID:{}, 原因{}", correlationData.getId(), ex.getMessage())
        );
        // 4、发送消息
        rabbitTemplate.convertAndSend("seckill_exchange", "seckill.order", message, correlationData);
    }

    /**
     * 优惠券秒杀
     */
    @Override
    public Result seckillVoucher(Long voucherId) {
        // 获取用户
        Long userId = UserHolder.getUser().getId();
        // 1、执行lua脚本 -- 判断一人一单
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString()
        );
        // 2、判断结果是否为0
        int r = result.intValue();
        if (r != 0) {
            // 2.1、不为0，没有购买资格
            return Result.fail(r == 1 ? "库存不足" : "不能重复下单");
        }
        // 2.2、为0，有购买资格，把下单信息保存到阻塞队列
        VoucherOrder voucherOrder = new VoucherOrder();
        // 2.3、订单id
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
        // 2.4、用户id
        voucherOrder.setUserId(userId);
        // 2.5、代金券id
        voucherOrder.setVoucherId(voucherId);
        // 3、获取代理对象
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        // 4、 rabbitMQ发送信息
        sendMessageToQueue(JSONUtil.toJsonStr(voucherOrder));
        // 5、返回订单id
        return Result.ok(orderId);
    }

    @NotNull
    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        //5、一人一单
        Long userId = voucherOrder.getUserId();
        //5.1、查询订单
        Long count = query().eq("user_id", userId).eq("voucher_id", voucherOrder.getVoucherId()).count();
        //5.2、判断是否存在
        if (count > 0) {
            // 用户已经购买过了
            log.error("用户已经购买过一次！");
            return;
        }
        //6、扣减库存
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1") //set stock = stock - 1
                .eq("voucher_id", voucherOrder.getVoucherId()).gt("stock", 0) // where id = ? and stock > 0
                .update();
        if (!success) {
            //扣减失败
            log.error("库存不足");
            return;
        }
        //7、创建订单
        save(voucherOrder);
    }
}









